package io.kiki.task.server.job.task.support.executor.job;

import akka.actor.ActorRef;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import io.kiki.task.common.core.enums.JobTaskTypeEnum;
import io.kiki.task.server.common.akka.ActorGenerator;
import io.kiki.task.server.common.exception.JobServerException;
import io.kiki.task.server.common.util.ClientInfoUtils;
import io.kiki.task.server.job.task.dto.RealJobExecutorDTO;
import io.kiki.task.server.job.task.support.JobTaskConverter;
import io.kiki.task.template.datasource.persistence.po.JobTask;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class ClusterJobExecutor extends AbstractJobExecutor {

    @Override
    public JobTaskTypeEnum getTaskInstanceType() {
        return JobTaskTypeEnum.CLUSTER;
    }

    @Override
    protected void doExecute(JobExecutorContext context) {

        // 调度客户端
        List<JobTask> taskList = context.getTaskList();
        if (CollUtil.isEmpty(taskList)) {
            throw new JobServerException("No executable job task");
        }

        JobTask jobTask = taskList.get(0);
        if (StrUtil.isBlank(jobTask.getClientInfo())) {
            return;
        }
        RealJobExecutorDTO realJobExecutor = JobTaskConverter.INSTANCE.toRealJobExecutorDTO(context, jobTask);
        realJobExecutor.setClientId(ClientInfoUtils.clientId(jobTask.getClientInfo()));
        ActorRef actorRef = ActorGenerator.jobRealTaskExecutorActor();
        actorRef.tell(realJobExecutor, actorRef);

    }

}
